#include "stdafx.h"
#define VERSION "0.04"  // change this when change something in code!!!

#include "../common.h"

#include "pathfind.h"

#include "typs.h"
#include "array.hpp"
#include "errorm.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "3d/vector2.h"
#include "3d/vector2.h"

#include "ase/ase_terrain.h"
#include "ase/ase_threatboard.h"
#include "ase/ase_search.h"
#include "ase/ase_losapproxboard.h"

#include "ase/PathFinder.h"
#include "ase/refptr.h"
#include "cells.h"
#include "passmap.h"
//#include  "Wm3Vector2.h"

//#include "ase/RoadMap.h"

#include  <list>

using namespace std;
//
//   external data
// +-----------+--------+-----------+----+----+----+----+----+
// |highwayRoad|railRoad|countryRoad|  landType    |  ?????  |
// +-----------+--------+-----------+----+----+----+----+----+
//   7           6        5           4    3    2    1    0
//
//   static data
// +----+------+-----------+--------+-----------+-------+---------+-----+
// |    |bridge|highwayRoad|railRoad|countryRoad|montain|deepwater|water|   
// +----+------+-----------+--------+-----------+-------+---------+-----+
//   7    6      5           4        3           2       1         0
//
//   dinamical data
// +----------+-----------+------+-------+----+----+----+----+
// |goodbridge|notendpoint|unpass|fastway|  **parent**  |free|
// +----------+-----------+------+-------+----+----+----+----+
//   7          6           5      4       3    2    1    0
//














//==========================================================================


static int firstrun_pmaps = 1;
static PassMap* pmap[N_SIMULTANEOUS_PATHES];


static void free_pmaps() {
  for(int i=0; i<N_SIMULTANEOUS_PATHES; i++) {
    if(pmap[i]) {
      if(!firstrun_pmaps) {
        delete pmap[i];
      }
      pmap[i] = 0;
    }
  }
  firstrun_pmaps = 0;
}

static int wrong_pmap(int pathIdx) {
  return   ( pathIdx<0 )
        || ( pathIdx>=N_SIMULTANEOUS_PATHES )
        || ( !pmap[pathIdx] )
        || ( pmap[pathIdx]->NoInit() );
}

bool	PathFind_IsWater(int X, int Y)
{

	
	return false;
}

bool PathFind_iswater(double x,double y){return PassMap::iswater(x,y);};
bool PathFind_ismountain(double x,double y){return PassMap::ismountain(x,y);};
bool PathFind_israil(double x,double y){return PassMap::israil(x,y);};
bool PathFind_isroad(double x,double y){return PassMap::isroad(x,y);};
bool PathFind_ishighway(double x,double y){return PassMap::ishighway(x,y);};
bool PathFind_isforest(double x,double y){return PassMap::isforest(x,y);};
bool PathFind_isgrass(double x,double y){return PassMap::isgrass(x,y);};
bool PathFind_isbridge(double x,double y){return PassMap::isbridge(x,y);};

void PathFind_SetMap(const unsigned char *mapData, 
                     unsigned char outsideMapCell,
                     int width, int height,
                     float cellSize, float roadWidth,
                     ExternalBridgeInfo *extBr, int nBridges, int movertype) {
  int i;

  free_pmaps();

  //init roads here.

 // RoadMap* pRoadMap;
 // pRoadMap = new RoadMap();//
 // delete pRoadMap;
  //TODO here I should add some information on 

  

  PassMap::BuildStatMap( (const ExternalCell*)mapData, 
                         (const ExternalCell*)&outsideMapCell,
                         width, height,
                         cellSize, roadWidth,
                         extBr, nBridges );
//moved up - will it change something?
  int err = 0;
  PassMap::InitSize(width,height);//also set it inited
  for(i=0; i<N_SIMULTANEOUS_PATHES; i++) {
		     pmap[i] = new PassMap();    //lately do something with memory currently just reuse the passmapstatic
    if( wrong_pmap(i) ) {
      err = 1;
    }
  }
  //??
if(err) {
    free_pmaps();
    PassMap::ResetGlobal();
    return;
  }

//TODo so temp init internal maps for the PassMaps. use statMap of PassMap to init my internal structs and see how they could be interchanged.

for(i=0; i<N_SIMULTANEOUS_PATHES; i++) {
    pmap[i]->InitPaths(movertype);
    }

}


//=======================================================================

//check point on the road.
PassMap::terTypes checkThePointOnTheRoad(int pathIdx,PathNode& _pppath) 
{
	unsigned char type;

	type = pmap[pathIdx]->GetTerrainBoard()->GetCellValue(_pppath.col,_pppath.row);
	switch(type) {
		case  PassMap::HIGHWAY : return PassMap::HIGHWAY; break;
		case  PassMap::ROAD :    return PassMap::ROAD; break;
		default : return PassMap::GRASS;break;
	}


}

//check for pairs
int  checkRoadSegmentPairs(int pathIdx,PathNode* _pppath,PathNode* _pathnext,int& state)
{
//check both for the road
	unsigned char type1,type2;
	if(_pathnext!=0)
	{
	type1 = checkThePointOnTheRoad(pathIdx,*_pppath);
	type2 = checkThePointOnTheRoad(pathIdx,*_pathnext);
	}
	else
	{
		type1 = checkThePointOnTheRoad(pathIdx,*_pppath);
		type2 = type1;
	}
	if (type1 == type2)
	{
		if(type1==PassMap::GRASS)
		{
			//put the first into grass
			//return operation put the first into grass and continue
			state=1;//grass  //1 grass 2 hightway 3 road
			return 1;//both go into list grass.
		}

		if(type1==PassMap::HIGHWAY)
		{
			//put it into hightway and continue
			state=2;////1 grass 2 hightway 3 road
			return 2;//both go into list hightway
		}
		if(type1==PassMap::ROAD)
		{
			//put it into roads and continue
			state=3;////1 grass 2 hightway 3 road
			return 3;//both go into list road
		}

	}
	else
	{
		if(type1==PassMap::GRASS)
		{
			//put the first into grass and also add next as approximation to road then finish
			if(type2==PassMap::HIGHWAY)
			{
				state=2;////1 grass 2 hightway 3 road
				return 4;//first goes into grass and also one node is added - to be interpolated up to the road ( so somehow I should deal with the situation)
				//second goes into highway  list ( new one ).
			}
			if(type2==PassMap::ROAD)
			{
				state=3;////1 grass 2 hightway 3 road
				return 5;	//first goes into grass and also one node is added - to be interpolated up to the road ( so somehow I should deal with the situation)
				//second goes into road list ( new one ).						
			}
			return 0;//error
		}

		if(type1==PassMap::HIGHWAY)
		{
			//put the first into highway and also add next as approximation to road then finish
			if(type2==PassMap::GRASS)
			{
				state=1;////1 grass 2 hightway 3 road
				return 6;//first goes into hightway and also one node is added to the grass ( the first node ) - to be interpolated from  the road ( so somehow I should deal with the situation)
				//second goes into grass as a second node.
			}
			if(type2==PassMap::ROAD)
			{
				state=3;////1 grass 2 hightway 3 road
				return 7;//first goes into highway and also one node is added to the road list ( the first node ) - to be interpolated from  the hightway ( here I should check crossings...) ( so somehow I should deal with the situation)
				//second goes into grass as a second node.).							
			}
			return 0;//error
			
		}
		if(type1==PassMap::ROAD)
		{
			//put the first into grass and also add next as approximation to road then finish
			if(type2==PassMap::HIGHWAY)
			{
				state=2;//1 grass 2 hightway 3 road
				return 8;
				///first goes into road  and also one node is added to the hightway list ( the first node ) there should be a crossing here - if not crossing there should be error. - to be interpolated from  the hightway ( here I should check crossings...) ( so somehow I should deal with the situation)
				//second goes into grass as a second node.).	
			}
			if(type2==PassMap::GRASS)
			{
				state=1;////1 grass 2 hightway 3 road
				return 9;	//first goes into road and also one node is added to the grass list ( the first node ) - to be interpolated from  the road
				//second goes into grass as a second node.).							
			}
			return 0;//error
		}

	}
return 0;//error
}











void PathFind_UnloadMap() {
  free_pmaps();
  PassMap::ResetGlobal();
}

int PathFind_SetMoverType(int movertype) {
  if((movertype<0) || (movertype>=N_MOVER_TYPES)) {
    return 0;
  }
  if(movertype!=PassMap::GetMoverType()) {
    PassMap::SetMoverType(movertype);
    for(int i=0; i<N_SIMULTANEOUS_PATHES; i++) {
      if( !wrong_pmap(i) ) {
        //pmap[i]->CleanupMap(movertype);
        pmap[i]->cachedStartPos.set( -1, -1 );
      }
    }
  }
  return 1;
}


int PathFind_SetStartPoint(int pathIdx, float posX, float posY) {
  if( wrong_pmap(pathIdx) ) {
    return 0;
  }

  pmap[pathIdx]->worldBeginPos.set( posX, posY );
  int inside = PassMap::clip_isInside( pmap[pathIdx]->worldBeginPos );
  pmap[pathIdx]->worldBeginPosIsGood = 0;

 // if( inside ) {
    if(PassMap::GetMoverType() == MOVER_TRAIN) {
      pmap[pathIdx]->cnvCoordSystem_CellCenter(posX, posY);
    }else {
      pmap[pathIdx]->cnvCoordSystem(posX, posY);
    }

	
    int x = (int)posX;
    int y = (int)posY;

    if( pmap[pathIdx]->cantbeendpointCell(x,y) ) {
      return 0;
    }
  //}else { // outside - TODO will fix here later
  //  if( PassMap::outside_cantbeendpointCell() ) {
  //    return 0;
  //  }
  //}


  //TODO here insert the start init code for a*.
 //  will store as   provided float transferred ccords will try to use the info.

	
  //posX and posY are set in convcoords.
  pmap[pathIdx]->m_refptrAstar->setStartPoint(posX,posY);//TODO again - here I miss the opportunity to use floats will fix later when all things will be done.

  pmap[pathIdx]->worldBeginPosIsGood = 1;
  return 1;
}


int PathFind_IsPointReacheable(int pathIdx, float posX, float posY) {
  if( wrong_pmap(pathIdx) ) {
    return 0;
  }

  if( !pmap[pathIdx]->worldBeginPosIsGood ) {
    return 0;
  }

  if(PassMap::GetMoverType() == MOVER_BUILDING) {
    return 0;
  }

  pmap[pathIdx]->worldEndPos.set( posX, posY );

  
  //there was code to clip = no need - I set up the whole map

  //TODO SK: next time change ( worldBegin pos is a position in  the world of the pos of the point

  //set here check for different cells. use the same code as cantbeendpointCell to determine cells ( all placement should be in different cells.)

  //if(
 // if( pmap[pathIdx]->worldBeginPos.distance( pmap[pathIdx]->worldEndPos ) 
 //     <= PassMap::cellSize * 0.05f ) {
 //   return 0; // too close
 // }


//TODO remove the check for inside - there all points will be   inside.
  //I will have trains and will come here one more time...
    if(PassMap::GetMoverType() == MOVER_TRAIN) {//check if there would be trains... ( but wopuld there the trains ?) I think no.
     pmap[pathIdx]->cnvCoordSystem_CellCenter(posX, posY);
    }else {
      pmap[pathIdx]->cnvCoordSystem(posX, posY);
    }
    int x = (int)posX;
    int y = (int)posY;
    if( pmap[pathIdx]->cantbeendpointCell(x,y) ) {
      return 0; // good check if I can put point onto the river.
    }
 

  //pmap[pathIdx]->m_refptrAstar->GeneratePath(
  //convert coords here for me
  //int _posX(posX),_posY(posY);
  // pmap[pathIdx]->cnvCoordSystem(posX,posY);//I need this but placing here it is OK to  - just remove obsolete inside checks.
 // I could use only in making path function - not here but PathFind_BuildPath
  pmap[pathIdx]->m_refptrAstar->setEndPoint(posX,posY);//TODO again - here I miss the opportunity to use floats will fix later when all things will be done.
  //I'm not intended to search for more where it is set...
  //


  //TODO SK: 
  //I prefer to add either to support zero finided way in next step ( I think it is quite possible - I should see how it is orginised in java)
  //so that I just perform the same way as if I returned no way in PathFind_IsPointReacheable or to add here speed lookup if there is a way. 

   //if(pmap[pathIdx]->m_refptrAstar->GeneratePath())
   //{
     return 1;//TODO actually here I would rather speed up the process using look up tables - I do not need to run the code just to check.
  // }
   
	//return 0;////TODO actually here I would rather speed up the process using look up tables.
   
}



PathNode *PathFind_BuildPath(int pathIdx,float posX,float posY,int *res_nNodes,int minlen){
  if(!res_nNodes) {
    return 0;
  }
  if( wrong_pmap(pathIdx) ) {
    return 0;
  }

  if( !pmap[pathIdx]->worldBeginPosIsGood ) {
    return 0;
  }

  if(PassMap::GetMoverType() == MOVER_BUILDING) {
    return 0;
  }

  //reduntant checks - already done.
  /*pmap[pathIdx]->worldEndPos.set( posX, posY );
  int inside = PassMap::clip_isInside( pmap[pathIdx]->worldEndPos );*/

  //if( pmap[pathIdx]->worldBeginPos.distance( pmap[pathIdx]->worldEndPos ) 
  //    <= PassMap::cellSize * 0.05f ) {
  //  return 0; // too close
  //}

  //if( inside ) {
    if(PassMap::GetMoverType() == MOVER_TRAIN) {
      pmap[pathIdx]->cnvCoordSystem_CellCenter(posX, posY);
    }else {
      pmap[pathIdx]->cnvCoordSystem(posX, posY);
    }
    int x = (int)posX;
    int y = (int)posY;
    if( pmap[pathIdx]->cantbeendpointCell(x,y) ) {
      return 0;
    }
  //}else { // outside
  //  if( PassMap::outside_cantbeendpointCell() ) {
  //    return 0;
  //  }
  //}

  //TODO 
  
  //convert coords here for me
  //int _posX(posX),_posY(posY);
 // pmap[pathIdx]->cnvCoordSystem(posX,posY);
  pmap[pathIdx]->m_refptrAstar->setEndPoint(posX,posY);//TODO again - here I miss the opportunity to use floats will fix later when all things will be done.
  //I'm not intended to search for more where it is set...




  //Array<PathNode>* ppath = MakePath( 0, *pmap[pathIdx] );

  //TODO now make the path as it goes here.
  

  if(pmap[pathIdx]->m_refptrAstar->GeneratePath())//start and end points are set.
  {
	  //could find
	  //otherwise could not
  


  //
    

  
	_asNode *best =  pmap[pathIdx]->m_refptrAstar->GetBestNode();//first point so _asNode should have something to support
	//float points. as a test if not optimize latest - by each step compare the pixels.
	/*PathNode* tempnode;*/
	//for(int i=0; i<ppath->N()-1; i++) {
	//	tempnode= &(*ppath)[i];
 //         //i--; 
 //       }  

	int x1,y1,px,py;
//first pass - compute number of nodes.

	int counter(0);
	//if (best) {
	//	counter=1;
	//	x1 = best->GetX();
	//	y1 = best->GetY();
	//	best = best->GetParent();
	//}
	while (best) {
	//	x1 = best->GetX();
	//	y1 = best->GetY();
		best = best->GetParent();
		counter++;//now we found all nodes.

		if (counter > minlen && minlen !=0)
			return 0;
	}
	//now set up from back to forth
	//again get best from the top
	best =  pmap[pathIdx]->m_refptrAstar->GetBestNode();
	//if(counter) {
	Point2f startpoint,endpoint,point; //separately start and end nodes
	startpoint.set( pmap[pathIdx]->m_refptrAstar->startX,pmap[pathIdx]->m_refptrAstar->startY);
	endpoint.set( pmap[pathIdx]->m_refptrAstar->endX,pmap[pathIdx]->m_refptrAstar->endY);

	//easier to allocate an array and return it. then delete.... or just replace existing values...
	//later on change the behaviour....
	PathNode* _pppath(0);
	_pppath = new PathNode[counter];//then delete (actually i can make pathNode be reference counted.



	for(int j=counter-1;j>=0;j--)
	{
		//special cases - start and end

		//if(j==(counter-1))//startnode
		//{
		//	_pppath[j]=PathNode(startpoint);
		//	continue;
		//}
		if(j==0)//endnode
		{
			_pppath[j]=PathNode(startpoint);//no need to make two separate. these pathnodes should go to hell...
			//should be equal to the end.
			continue;
		}//endpoint

		//point.set 
		//create node ( here should need an algo for starting end etc nodes) and add
		//if(j==0)
		//{
		//pppath->Add(PathNode(startPosEnd)); continue;
		//}

		_pppath[j]=PathNode(best->GetX(),best->GetY());
		best = best->GetParent();//circle counter should provide entire convertion
	}


	//here I will do the following : first find points in and out on the roads.
	//
	//check the road.
	//check the first road point is it on the road?
//develop pairs of nodes ( their i ) off road on road.
	
	
	//check cell value if it is road ( develop a function )
//here we have three lists - list of nodes on offroad, list of nodes on highway and list on simple road

	//later I can change - istead of double resort I can make - push front - such that I will have nodes being sorted right order.
//list<PathNode*>* _list;
//list<PathNode*>* curlist;
////push data into list.
//
//list< list<PathNode*>* > grasspaths;
//list< list<PathNode*>* > highwaypaths;
//list< list<PathNode*>* > roadpaths;
////found a problem while adding new nodes and deleleting them then - I  have the problems.
//int state(0),_state,prevstate;
//for(int j=0;j<counter;j++)
//{
//	//so now watch for dealing with the last element...
//	int result;
//	if(j==counter-1)
//	{
//	result  = checkRoadSegmentPairs( pathIdx,&_pppath[j],&_pppath[j+1],_state);
//	}
//	else
//	{
//		result  = checkRoadSegmentPairs( pathIdx,&_pppath[j],0,_state);
//	}
//	
//	//check 
//	//now make a decision conserning additions.
//	//state - current list
//	if(j==0)
//	{
//		//init state here....
//		//1 grass 2 hightway 3 road
//		//if(result==1 || result==4 || result==
//		state=prevstate=_state;
//		//create an initial list
//	_list= new list<PathNode*>;
//	curlist=_list;
//	if(state==1)
//	{
//		grasspaths.push_back(curlist);////1 grass 2 hightway 3 road
//	}
//	if(state==2)
//	{
//		highwaypaths.push_back(curlist);
//	}
//	if(state==3)
//	{
//		roadpaths.push_back(curlist);
//
//	}
//
//
//	}
//
//	switch (result)
//	{
//	case 1: //put the first into grass
//			//return operation put the first into grass and continue
//			//both go into list grass.
//		{
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				curlist->push_back(&_pppath[j]);
//				grasspaths.push_back(curlist);
//
//			}
//			else
//			{
//				curlist->push_back(&_pppath[j]);
//			}
//			//prevstate=state;
//			break;
//		}
//	case 2://put it into hightway and continue
//			//both go into list hightway
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				highwaypaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//
//			}
//			else
//			{
//				curlist->push_back(&_pppath[j]);
//			}
//		//	prevstate=state;
//			break;
//
//		}
//	case 3://put it into roads and continue
//			//both go into list road
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				roadpaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//
//			}
//			else
//			{
//				curlist->push_back(&_pppath[j]);
//			}
//		//	prevstate=state;
//			break;
//
//		}
//	case 4://first goes into grass and also one node is added - to be interpolated up to the road ( so somehow I should deal with the situation)
//				//second goes into highway  list ( new one ).
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//
//			}
//			else
//			{
//				curlist->push_back(&_pppath[j]);
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//			}
//
//		//prevstate=2;//hightway
//		break;
//
//		}
//	case 5://first goes into grass and also one node is added - to be interpolated up to the road ( so somehow I should deal with the situation)
//				//second goes into road list ( new one ).	
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//
//			}
//			else
//			{
//				curlist->push_back(&_pppath[j]);
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//
//			}
//		//	prevstate=3;//road
//			break;
//
//		}
//
//	case 6://first goes into hightway and also one node is added to the grass ( the first node ) - to be interpolated from  the road ( so somehow I should deal with the situation)
//				//second goes into grass as a second node.
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				highwaypaths.push_back(curlist);// the road ended we change the state.
//				curlist->push_back(&_pppath[j]);
//				prevstate=1;//grass...
//				// we start a new path here
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);				
//				//and the second is also marked as interpolated.
//
//				
//			}
//			else
//			{
//				//highwaypaths.push_back(curlist);// the road ended we change the state.
//				prevstate=1;//grass...
//				// we start a new path here
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//
//
//			}
//	//prevstate=1;//grass...
//	break;
//		}
//	case 7:////first goes into highway and also one node is added to the road list ( the first node ) - to be interpolated from  the hightway ( here I should check crossings...) ( so somehow I should deal with the situation)
//				//second goes into grass as a second node.).	
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				highwaypaths.push_back(curlist);// the road ended we change the state.
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				roadpaths.push_back(curlist);
//
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);
//
//				///continuation flag ??
//				//and the second is also marked as interpolated.
//				
//
//
//			}
//			else
//			{
//				highwaypaths.push_back(curlist);// the road ended we change the state.
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				roadpaths.push_back(curlist);
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);//and the second is also marked as interpolated.
//				
//			}
//			//prevstate=3;//road...
//			break;
//		}
//	case 8:///first goes into road  and also one node is added to the hightway list ( the first node ) there should be a crossing here - if not crossing there should be error. - to be interpolated from  the hightway ( here I should check crossings...) ( so somehow I should deal with the situation)
//				//second goes into grass as a second node.).
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				roadpaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				highwaypaths.push_back(curlist);
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);
//
//				//continuation flag ??
//				//and the second is also marked as interpolated.
//				
//
//			}
//			else
//			{
//				roadpaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				highwaypaths.push_back(curlist);
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);
//
//				//continuation flag ??
//				//and the second is also marked as interpolated.
//				
//
//
//			}
//		//	prevstate=2;//hightway...
//			break;
//		}
//	case 9:
//		//first goes into road and also one node is added to the grass list ( the first node ) - to be interpolated from  the road
//		//second goes into grass as a second node.).	
//		{
//			//check
//			if(state!=prevstate)//
//			{
//				//create new grass list
//				_list= new list<PathNode*>;
//				curlist=_list;
//				roadpaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//				//_pppath[j+1].b_approximation=true;
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);
//
//				//continuation flag ??
//				//and the second is also marked as interpolated.
//				
//
//			}
//			else
//			{
//				roadpaths.push_back(curlist);
//				curlist->push_back(&_pppath[j]);
//				_list= new list<PathNode*>;
//				curlist=_list;
//				grasspaths.push_back(curlist);
//				PathNode* tempnode = new PathNode(_pppath[j+1]);
//				tempnode->b_approximation=true;
//				curlist->push_back(tempnode);;//and the second is also marked as interpolated.
//				
//
//			}
//
//		}
//		//prevstate=1;//grass...
//		break;
//
//
//	}
//	prevstate=state;
//}//for j counter ? }//for for states.
////====================================
//	
//	//clean everything
//	list< list<PathNode*>* >::iterator start ;
//	list< list<PathNode*>* >::iterator end ;
//	list< list<PathNode*>* >::iterator loop;
//
////clean grasspaths
//start=grasspaths.begin();
//end=grasspaths.end();
//
//	for(loop = start;loop!=end;++loop)
//	{
//		list<PathNode*>* list_del= (*(loop));
//		//clean everything
//	list< PathNode*>::iterator _start ;
//	list<PathNode* >::iterator _end ;
//	list<PathNode* >::iterator _loop;
//	_start=list_del->begin();
//	_end=list_del->end();
//
//	delete list_del;
//	
//	/*for(_loop = _start;_loop!=_end;++_loop)
//	{
//		PathNode* tempnode;
//		tempnode=*_loop;
//		delete tempnode;
//	}*/
//
//	}
//
//	//clean roadpaths
//start=roadpaths.begin();
//end=roadpaths.end();
//
//	for(loop = start;loop!=end;++loop)
//	{
//		list<PathNode*>* list_del= (*(loop));
//		//clean everything
//	list< PathNode*>::iterator _start ;
//	list<PathNode* >::iterator _end ;
//	list<PathNode* >::iterator _loop;
//	_start=list_del->begin();
//	_end=list_del->end();
//	
//	delete list_del;
//	/*for(_loop = _start;_loop!=_end;++_loop)
//	{
//		PathNode* tempnode;
//		tempnode=*_loop;
//		delete tempnode;
//	}*/
//
//	}
//
//	//clean hightwaypaths
//start=highwaypaths.begin();
//end=highwaypaths.end();
//
//
//		for(loop = start;loop!=end;++loop)
//	{
//		list<PathNode*>* list_del= (*(loop));
//		//clean everything
//	list< PathNode*>::iterator _start ;
//	list<PathNode* >::iterator _end ;
//	list<PathNode* >::iterator _loop;
//	_start=list_del->begin();
//	_end=list_del->end();
//
//	delete list_del;
//	
//	/*for(_loop = _start;_loop!=_end;++_loop)
//	{
//		PathNode* tempnode;
//		tempnode=*_loop;
//		delete tempnode;
//	}*/
//
//	}	
//
//		
//		
////====================================




//for the last point just check where to add


	Array<PathNode> *pppath = PassMap::getClearedPath(counter);//the one which will be deleted when program is done.
	//copy
	for(int j=0;j<counter;j++)
		pppath->Add(_pppath[j]);

	pmap[pathIdx]->ConvertPathToWorld( *pppath );

  delete  [] _pppath;

  if( (!pppath) || (pppath->N() <= 0) )
  
    return 0;

	
  
  else
  {
	  *res_nNodes = pppath->N();
	return & ((*pppath)[0]);
  }

}
	return 0;

//commented 

//	//
//	//now before I return an array I perform the simplification step ( to make a function ?)
////////////////////////////////////////////////////////////////////////////
//	int iCtrlQuantity = counter;
//    //kIStr >> counteriCtrlQuantity;
//    cVector2d* akCtrl = new  cVector2d[iCtrlQuantity];
//    for (int i = 0; i < iCtrlQuantity; i++)
//    {
//		akCtrl[i].X() =  _pppath[i].col;
//        akCtrl[i].Y() = _pppath[i].row ;
//		
//    }
//
//    // create polyline connecting control points of input B-spline curve
//    double dFraction = 0.10;//one tenth...
//
//    int iLSCtrlQuantity;
//    cVector2d* akLSCtrl;
//	BSplineReduction2d(iCtrlQuantity,akCtrl,PassMap::m_iDegree,dFraction,
//        iLSCtrlQuantity,akLSCtrl);
////BSplineReduction2d
////BSplineCurve2d
//    BSplineCurve2d kSpline(iLSCtrlQuantity,akLSCtrl,PassMap::m_iDegree,false,true);
//    delete [] akLSCtrl;
//double dTime;
//delete [] _pppath;
////now again
//_pppath = new PathNode[iLSCtrlQuantity];
//
// for (int i = 0; i < iLSCtrlQuantity; i++)
// {
//	 dTime = i/(double)iLSCtrlQuantity;
//cVector2d kPos = kSpline.GetPosition(dTime);
//_pppath[i].set( (int) (kPos.X()), ( int ) (kPos.Y()));
// }
////now feed into .
//	//now I need to get from kSpline nessesary points.   and also prevent roads
//	//the solution might be - split to each bridge and return several paths.
//	// it is neccesary to see how further it is done ). so currently just reduce.
//
////    delete [] akCtrl;
////	//now fill it back.
////for (int i = 0; i < iCtrlQuantity; i++)
////    {
////		akCtrl[i].X() = _pppath[i].row ;
////        akCtrl[i].Y() = _pppath[i].col ;
////		
////    }
/////////////////////////////////////////////////////////////////////////////
//
////now create an array to return
//
//	Array<PathNode> *pppath = PassMap::getClearedPath(iLSCtrlQuantity);//the one which will be deleted when program is done.
//	//copy
//	for( j=0;j<iLSCtrlQuantity;j++)
//		pppath->Add(_pppath[j]);
//
//	pmap[pathIdx]->ConvertPathToWorld( *pppath );
//
//  delete  [] _pppath;
//
//  if( (!pppath) || (pppath->N() <= 0) ) {
//    return 0;
//
//	
//  }
//  else
//  {
//	  *res_nNodes = pppath->N();
//	return & ((*pppath)[0]);
//  }
//
//  
//	}//if (counter)
//	}//if generatepath
//	
//	  return 0;
    
  //return & ((*_ppath)[0]);
  


}
